<template>
  <div style="padding: 20px;">
    <item-title title="取样点" :borderShow="false"/>
    <div>
      <el-form
        style="width: 100%; display: flex; justify-content: space-between"
        ref="queryForm"
        :model="queryForm"
        :inline="true"
        label-width="100px"
      >
        <div>
          <el-form-item label="">
            <el-select
              style="width: 400px"
              v-model="queryForm.type"
              placeholder="全部考察类型"
              clearable
              size="small"
              @change="handleQuery"
            >
              <el-option
                v-for="(item, index) in values"
                :key="index"
                :label="item.inspect_type_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div style="float: right">
          <el-form-item>
            <el-button type="primary" icon="el-icon-plus" @click="addSample"
              >添加取样点</el-button
            >
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div>
      <el-table :data="data" size="medium" border>
        <el-table-column
          label="考察类型"
          align="center"
          prop="inspect_type_name"
        ></el-table-column>
        <el-table-column
          label="放置条件类型"
          align="center"
          prop="place_conditions_type_name"
        ></el-table-column>
        <el-table-column label="取样点" align="center" prop="sample_point_info">
          <template slot-scope="scope" v-if="scope.row.sample_point_info">
            <div
              style="display: flex; flex-wrap: wrap; justify-content: center"
            >
              <div
                v-for="(item, index) in scope.row.sample_point_info"
                :key="index"
              >
                {{ item.sample_point_num }}
                <span v-if="item.sample_point_unit == 1">天</span>
                <span v-if="item.sample_point_unit == 2">月</span>
                <span v-if="scope.row.sample_point_info.length - 1 != index"
                  >,</span
                >
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" 
            align="left"
            header-align="center"
            width="180">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="meduim"
              @click="editSample(scope.row)"
              >编辑
            </el-button>
            <el-button
              class="text-btn-red"
              type="text"
              size="meduim"
              @click="deleteItem(scope.row, scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        style="display: flex; justify-content: flex-end"
        :total="total"
        :page.sync="pages.pageNum"
        :limit.sync="pages.pageSize"
        @pagination="afreshList"
      />
    </div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :destroy-on-close="true"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="考察类型" prop="name">
          <el-select
            style="width: 100%"
            v-model="form.name"
            placeholder="考察类型"
            clearable
            size="small"
            @change="selectName"
          >
            <el-option
              v-for="(item, index) in values"
              :key="index"
              :label="item.inspect_type_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="放置条件类型" prop="type">
          <el-select
            style="width: 100%"
            v-model="form.type"
            placeholder="放置条件类型"
            clearable
            size="small"
            @change="selectType"
          >
            <el-option
              v-for="(item, index) in values1"
              :key="index"
              :label="item.place_conditions_type_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <div>
          <el-row style="margin-top: 10px; padding-left: 10px">
            <el-col :span="7">
              <div>取样点</div>
            </el-col>
            <el-col :span="7">
              <div>取样单位</div>
            </el-col>
            <el-col :span="7">
              <div>取样时限上限（天）</div>
            </el-col>
          </el-row>
          <el-row
            style="margin-top: 2px;margin-left:2px"
            v-for="(item, index) in form.sample_point_info"
            :key="index"
          >
            <el-col :span="7">
              <el-form-item
                label-width="0"
                :prop="'sample_point_info.' + index + '.sample_point_num'"
                :rules="[
                  {
                    required: true,
                    message: '取样点不能为空',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="item.sample_point_num"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item
                label-width="0"
                :prop="'sample_point_info.' + index + '.sample_point_unit'"
                :rules="[
                  {
                    required: true,
                    message: '取样点单位为空',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  style="width: 200px"
                  v-model="item.sample_point_unit"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="(item, index) in valued"
                    :key="index"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item
                label-width="0"
                :prop="
                  'sample_point_info.' + index + '.ceiling_sample_point_num'
                "
                :rules="[
                  {
                    required: true,
                    message: '取样上限不能为空',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="item.ceiling_sample_point_num"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button
                type="text"
                size="meduim"
                v-if="index == form.sample_point_info.length-1"
                @click="addInputItem"
                >添加
              </el-button>
              <el-button
                class="text-btn-red"
               size="meduim"
                type="text"
                v-if="form.sample_point_info.length != 1"
                @click="deleteInputItem(index)"
                >删除
              </el-button>
            </el-col>
          </el-row>
          <!-- <el-row
                style="padding:10px"
                v-for="(item,index) in sample_point_info"
                :key="index"
              >
              <el-col :span='7'>
                  <el-input v-model="item.sample_point_num" style="width:200px"></el-input>
              </el-col>
              <el-col :span='7'>
                <el-select
                style="width: 200px"
                v-model="item.sample_point_unit"
                clearable
                size="small"
              >
                <el-option
                  v-for="(item, index) in valued"
                  :key="index"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
              </el-col>
              <el-col :span='7'>
                 <el-input v-model="item.ceiling_sample_point_num" style="width:200px"></el-input>
              </el-col>
              <el-col :span='3'>
                <el-button
                    icon="el-icon-plus"
                    type="text"
                    v-if="index==0"
                    @click="addInputItem"
                  >添加
                  </el-button>
                  <el-button
                    class="text-btn-red"
                    icon="el-icon-delete"
                    type="text"
                    v-if="index!=0"
                    @click="deleteInputItem(index)"
                  >删除
                  </el-button>
              </el-col>
         </el-row> -->
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="handleClose">取消</el-button>
        <el-button plain v-if="title == '添加取样点'" @click="cSubmitForm"
          >保存并继续添加</el-button
        >
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selectInvestigationList,
  sampleList,
  selectInvestigationfList,
  createSample,
  updateSample,
  deleteSample,
} from "@/api/stability";
export default {
  data() {
    let name = (rule, value, callback) => {
      if (this.form.name != "") {
        callback();
      } else {
        callback(new Error("请选择考察类型"));
      }
    };
    let type = (rule, value, callback) => {
      if (this.form.type != "") {
        callback();
      } else {
        callback(new Error("请选择放置条件类型"));
      }
    };
    return {
      title: "添加取样点",
      inputList: [
        {
          num: "",
          single: "1",
          limit: "",
        },
      ],
      tableForm: {},
      pages: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      activeName: "first",
      queryForm: {
        type: "",
        name: "",
      },
      valued: [
        {
          id: 1,
          label: "天",
        },
        {
          id: 2,
          label: "月",
        },
      ],
      current: null,
      isEdit: false,
      values: "",
      values1: "",
      current: null,
      data: [],
      open: false,
      form: {
        name: "",
        type: "",
        sample: "",
        single: "1",
        sample_point_info: [
          {
            sample_point_num: "",
            sample_point_unit: 2,
            ceiling_sample_point_num: "",
          },
        ],
      },
      rules: {
        name: [{ required: true, validator: name }],
        type: [{ required: true, validator: type }],
      },
      created_at: "",
      creator_id: "",
      creator_name: "",
      deleted_at: "",
      id: "",
      updated_at: "",
      inspect_type_id: "",
      inspect_type_name: "",
      place_conditions_type_name: "",
      place_conditions_type_id: "",
      sample_point_info: [
        {
          sample_point_num: "",
          sample_point_unit: "",
          ceiling_sample_point_num: "",
        },
      ],
    };
  },
  created() {
    this.getSelectType();
    this.getSampleList();
    this.getSelectfType();
  },
  methods: {
    handleQuery() {
      this.pages={
        pageNum:1,
        pageSize:10
      },
      this.getSampleList();
    },
    addInputItem() {
      this.form.sample_point_info.push({
        sample_point_num: "",
        sample_point_unit: 2,
        ceiling_sample_point_num: "",
      });
    },
    deleteInputItem(index) {
      this.form.sample_point_info.splice(index, 1);
    },
    afreshList() {
      this.getSampleList();
    },
    selectName() {
      console.log(this.form.name);
      this.inspect_type_id = this.form.name;
      this.values.forEach((item) => {
        if (this.form.name == item.id) {
          this.inspect_type_name = item.inspect_type_name;
        }
      });
    },
    selectType() {
      console.log(this.form.type);
      this.place_conditions_type_id = this.form.type;
      this.values1.forEach((item) => {
        if (this.form.type == item.id) {
          this.place_conditions_type_name = item.place_conditions_type_name;
        }
      });
    },
    //列表
    getSampleList() {
      let data = {
        inspect_type_id: this.queryForm.type,
        pager: {
          limit: this.pages.pageSize,
          skip: this.pages.pageNum,
        },
      };
      sampleList(data).then((res) => {
        if (res.code == 200) {
          this.data = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    //获取放置条件下拉
    getSelectfType() {
      selectInvestigationfList().then((res) => {
        if (res.code == 200) {
          console.log(res.data);
          this.values1 = res.data;
        }
      });
    },
    //获取考察类型
    getSelectType() {
      selectInvestigationList().then((res) => {
        if (res.code == 200) {
          console.log(res.data);
          this.values = res.data;
        }
      });
    },
    addSample() {
      this.open = true;
      this.title = "添加取样点";
      this.form.sample_point_info=[
          {
            sample_point_num: "",
            sample_point_unit: 2,
            ceiling_sample_point_num: "",
          },
        ]
    },
    editSample(row) {
      this.open = true;
      this.title = "编辑取样点";
      this.created_at = row.created_at;
      this.creator_id = row.creator_id;
      this.creator_name = row.creator_name;
      this.deleted_at = row.deleted_at;
      this.id = row.id;
      this.updated_at = row.updated_at;
      this.form.name = row.inspect_type_id;
      this.place_conditions_type_name = row.place_conditions_type_name,
      this.inspect_type_name = row.inspect_type_name;
      this.form.type = row.place_conditions_type_id;
      this.form.sample_point_info=[]
      row.sample_point_info.forEach((item) => {
        Object.assign(item, {
          sample_point_num: String(item.sample_point_num),
        });
        Object.assign(item, { sample_point_unit: item.sample_point_unit });
        Object.assign(item, {
          ceiling_sample_point_num: String(item.ceiling_sample_point_num),
        });
      });
      this.form.sample_point_info = JSON.parse(JSON.stringify(row.sample_point_info));
    },
    handleClose() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.$refs.form.clearValidate();
      this.$refs.form.resetFields();
      this.form = {
        name: "",
        type: "",
        sample_point_info: [
          // {
          //   sample_point_num: "",
          //   sample_point_unit: 1,
          //   ceiling_sample_point_num: "",
          // },
        ],
      };
    },
    deleteItem(row, index) {
      this.$confirm("是否确认删除 " + row.inspect_type_name + " ?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteSample(row.id).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.getSampleList();
            }else{
                this.$message.error(res.msg)
              }
          });
        })
        .catch(function () {});
    },
    cSubmitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.sample_point_info.forEach((item) => {
            Object.assign(item, {
              sample_point_num: Number(item.sample_point_num),
            });
            Object.assign(item, {
              sample_point_unit: Number(item.sample_point_unit),
            });
            Object.assign(item, {
              ceiling_sample_point_num: Number(item.ceiling_sample_point_num),
            });
          });
          if (this.title == "添加取样点") {
            let data = {
              inspect_type_id: this.form.name,
              inspect_type_name: this.inspect_type_name,
              place_conditions_type_name: this.place_conditions_type_name,
              place_conditions_type_id: this.form.type,
              sample_point_info: this.form.sample_point_info,
            };
            createSample(data).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.getSampleList();
                this.form = {
                  name: "",
                  type: "",
                  sample_point_info: [
                    {
                      sample_point_num: "",
                      sample_point_unit: 1,
                      ceiling_sample_point_num: "",
                    },
                  ],
                };
                this.$nextTick(() => {
                  this.$refs.form.clearValidate()
                })
              }else{
                this.$message.error(res.msg)
              }
            });
          }
        }
      });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var find = false;
          for (var i = 0; i < this.form.sample_point_info.length; i++) {
            for (var j = i + 1; j < this.form.sample_point_info.length; j++) {
              if (this.form.sample_point_info[i].sample_point_num == this.form.sample_point_info[j].sample_point_num&&this.form.sample_point_info[i].sample_point_unit == this.form.sample_point_info[j].sample_point_unit) {
                find = true;
                break;
              }
            }
            if (find) break;
          }
          // alert(find)
          if (find == true) {
            this.$message.error('存在取样值与取样单位相同')
            return
          }
          this.form.sample_point_info.forEach((item) => {
            Object.assign(item, {
              sample_point_num: Number(item.sample_point_num),
            });
            Object.assign(item, {
              sample_point_unit: Number(item.sample_point_unit),
            });
            Object.assign(item, {
              ceiling_sample_point_num: Number(item.ceiling_sample_point_num),
            });
          });
          if (this.title == "添加取样点") {
            let data = {
              inspect_type_id: this.form.name,
              inspect_type_name: this.inspect_type_name,
              place_conditions_type_name: this.place_conditions_type_name,
              place_conditions_type_id: this.form.type,
              sample_point_info: this.form.sample_point_info,
            };
            createSample(data).then((res) => {
              if (res.code == 200) {
                this.open = false;
                this.$message.success("添加成功");
                this.getSampleList();
                this.reset();
              }else{
                this.$message.error(res.msg)
              }
            });
          } else {
            let data = {
              id: this.id,
              created_at: this.created_at,
              creator_id: this.creator_id,
              creator_name: this.creator_name,
              deleted_at: this.deleted_at,
              updated_at: this.updated_at,
              inspect_type_id: this.form.name,
              inspect_type_name: this.inspect_type_name,
              place_conditions_type_name: this.place_conditions_type_name,
              place_conditions_type_id: this.form.type,
              sample_point_info: this.form.sample_point_info,
            };
            updateSample(data).then((res) => {
              if (res.code == 200) {
                this.open = false;
                this.$message.success("编辑成功");
                this.getSampleList();
                this.reset();
              }else{
                this.$message.error(res.msg)
              }
            });
          }
        }
      });
    },
    handleClick() {},
  },
};
</script>
<style lang="scss">

</style>